package com.erp.programmer.controller;


import com.erp.programmer.bean.CodeMsg;
import com.erp.programmer.dao.StockOrderMapper;
import com.erp.programmer.dto.PageDto;
import com.erp.programmer.dto.ProductDto;
import com.erp.programmer.dto.ResponseDto;
import com.erp.programmer.service.ProductService;
import com.erp.programmer.utils.CommonUtil;
import com.erp.programmer.utils.ValidateEntityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author czh
 * @since 2021-05-23
 */
@RestController
@CrossOrigin
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private StockOrderMapper stockOrderMapper;

    @PostMapping("/save")
    public ResponseDto<PageDto<ProductDto>> save(@RequestBody ProductDto productDto){

        if(productDto == null){
            return ResponseDto.errorByMsg(CodeMsg.DATA_ERROR);
        }
        //进行统一表单验证
        CodeMsg validate = ValidateEntityUtil.validate(productDto);
        if(!validate.getCode().equals(CodeMsg.SUCCESS.getCode())){
            return ResponseDto.errorByMsg(validate);
        }
        if(productDto.getStockOrderDto() == null || CommonUtil.isEmpty(productDto.getStockOrderDto().getWarehousePosition())){
            return ResponseDto.errorByMsg(CodeMsg.STOCK_NOT_EXIST);
        }
      /*  QueryWrapper<StockOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("warehouse_position", productDto.getStockOrderDto().getWarehousePosition());
        StockOrder stockOrderDb = stockOrderMapper.selectOne(queryWrapper);
        if(stockOrderDb == null){
            return ResponseDto.errorByMsg(CodeMsg.STOCK_NOT_EXIST);
        }*/
        if(CommonUtil.isEmpty(productDto.getId())){
            //添加
            ResponseDto<PageDto<ProductDto>> responseDto = productService.add(productDto);

            return responseDto;
        }else{
            //修改
            ResponseDto<PageDto<ProductDto>> responseDto = productService.edit(productDto);
            return responseDto;
        }
    }

    @PostMapping("/delete")
    public ResponseDto<PageDto<ProductDto>> delete(@RequestBody ProductDto productDto){

        if(productDto == null || CommonUtil.isEmpty(productDto.getId())){
            return ResponseDto.errorByMsg(CodeMsg.DATA_ERROR);
        }
        //进行统一表单验证
        CodeMsg validate = ValidateEntityUtil.validate(productDto);
        if(!validate.getCode().equals(CodeMsg.SUCCESS.getCode())){
            return ResponseDto.errorByMsg(validate);
        }

        ResponseDto<PageDto<ProductDto>> productDtos = productService.delete(productDto);

        return productDtos;
    }

    @PostMapping("/get_data")
    public ResponseDto<PageDto<ProductDto>> getAll(@RequestBody PageDto<ProductDto> pageDto){

        return productService.getAll(pageDto);
    }


}

